<template>
  <el-form :model="formData" label-width="120px">
    <el-form-item label="智能体名称" prop="name">
      <el-input v-model="formData.name" placeholder="请输入智能体名称" />
    </el-form-item>
    <el-form-item label="标识" prop="identifier">
      <el-input v-model="formData.identifier" placeholder="请输入标识" />
    </el-form-item>
    <el-form-item label="模型使用方式" prop="modelUsage">
      <el-radio-group v-model="formData.modelUsage">
        <el-radio label="fixed">固定模型</el-radio>
        <el-radio label="switchable">可切换模型</el-radio>
      </el-radio-group>
    </el-form-item>
    <el-form-item v-if="formData.modelUsage === 'fixed'" label="固定模型" prop="fixedModel">
      <el-select v-model="formData.fixedModel" placeholder="请选择模型">
        <el-option
          v-for="model in models"
          :key="model.id"
          :label="model.name"
          :value="model.id"
        />
      </el-select>
    </el-form-item>
    <el-form-item label="流式输出" prop="streamOutput">
      <el-switch v-model="formData.streamOutput" />
    </el-form-item>
    <el-form-item label="背景提示词" prop="backgroundPrompt">
      <el-input
        v-model="formData.backgroundPrompt"
        type="textarea"
        :rows="4"
        placeholder="请输入背景提示词"
      />
    </el-form-item>
    <el-form-item label="提示词模板" prop="scenePrompt">
      <el-input
        v-model="formData.scenePrompt"
        type="textarea"
        :rows="4"
        placeholder="请输入提示词模板"
      />
    </el-form-item>
    <el-form-item label="欢迎引导消息" prop="welcomeMessage">
      <el-radio-group v-model="formData.welcomeMessage">
        <el-radio label="show">显示</el-radio>
        <el-radio label="hide">隐藏</el-radio>
      </el-radio-group>
    </el-form-item>
    <template v-if="formData.welcomeMessage === 'show'">
      <el-form-item label="提示语内容" prop="promptContent">
        <el-input
          v-model="formData.promptContent"
          placeholder="请输入提示语内容"
        />
      </el-form-item>
      <el-form-item label="推荐引导词" prop="recommendedPrompts">
        <div class="recommended-prompts">
          <el-table :data="formData.recommendedPrompts" style="width: 100%" empty-text="暂无数据">
            <el-table-column prop="name" label="提示语名称">
              <template #default="scope">
                <el-input v-model="scope.row.name" placeholder="请输入提示语名称" />
              </template>
            </el-table-column>
            <el-table-column label="操作" width="100">
              <template #default="scope">
                <el-button
                  type="danger"
                  link
                  @click="handleDeletePrompt(scope.$index)"
                >
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
          <div class="add-prompt">
            <el-button
              type="primary"
              @click="handleAddPrompt"
              :disabled="formData.recommendedPrompts.length >= 5"
            >
              添加推荐引导词
            </el-button>
            <span class="prompt-tip" v-if="formData.recommendedPrompts.length >= 5">
              最多只能添加5条推荐引导词
            </span>
          </div>
        </div>
      </el-form-item>
    </template>
    <el-form-item label="文件上传" prop="fileUpload">
      <el-switch v-model="formData.fileUpload" />
    </el-form-item>
    <el-form-item label="向量知识库" prop="vectorStores">
      <div class="vector-stores">
        <el-table :data="formData.vectorStores" style="width: 100%" empty-text="暂无数据">
          <el-table-column prop="name" label="知识库名称" />
          <el-table-column label="操作" width="200">
            <template #default="scope">
              <el-button
                type="primary"
                link
                @click="handleEditVectorStore(scope.row)"
              >
                编辑
              </el-button>
              <el-button
                type="danger"
                link
                @click="handleDeleteVectorStore(scope.$index)"
              >
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <div class="add-vector-store">
          <el-button type="primary" @click="handleAddVectorStore">
            添加向量知识库
          </el-button>
        </div>
      </div>
    </el-form-item>
    <el-form-item label="引用函数" prop="referencedFunctions">
      <el-select
        v-model="formData.referencedFunctions"
        multiple
        placeholder="请选择函数"
      >
        <el-option
          v-for="func in functions"
          :key="func.id"
          :label="func.name"
          :value="func.id"
        />
      </el-select>
    </el-form-item>
  </el-form>

  <el-dialog
    v-model="vectorStoreDialogVisible"
    :title="isEditing ? '编辑向量知识库关联' : '添加向量知识库关联'"
    width="500px"
  >
    <el-form
      v-if="currentVectorStore"
      :model="currentVectorStore"
      label-width="120px"
    >
      <el-form-item label="关联向量知识库" prop="id">
        <el-select v-model="currentVectorStore.id" placeholder="请选择向量知识库">
          <el-option
            v-for="store in vectorStores"
            :key="store.id"
            :label="store.name"
            :value="store.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="最大结果数" prop="maxResults">
        <el-input-number
          v-model="currentVectorStore.maxResults"
          :min="1"
          :max="100"
          :step="1"
          controls-position="right"
        />
      </el-form-item>
      <el-form-item label="匹配阈值" prop="similarityThreshold">
        <el-input-number
          v-model="currentVectorStore.similarityThreshold"
          :min="0"
          :max="1"
          :step="0.1"
          :precision="2"
          controls-position="right"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="vectorStoreDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSaveVectorStore">
          确定
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script lang="ts">
import { defineComponent, reactive, ref, watch } from 'vue';
import { useModelsStore } from '@/store/models';
import { useFunctionsStore } from '@/store/functions';
import type { Agent } from '@/store/agents';
import type { Model } from '@/store/models';
import type { CustomFunction } from '@/store/functions';

interface VectorStore {
  id: string;
  name: string;
  maxResults: number;
  similarityThreshold: number;
}

export default defineComponent({
  name: 'AgentDetail',
  props: {
    modelValue: {
      type: Object as () => Agent,
      required: true
    }
  },
  emits: ['update:modelValue'],
  setup(props, { emit }) {
    const modelsStore = useModelsStore();
    const functionsStore = useFunctionsStore();
    
    const formData = reactive<Agent>({ ...props.modelValue });
    const models = ref<Model[]>([]);
    const functions = ref<CustomFunction[]>([]);
    const vectorStores = ref<{ id: string; name: string }[]>([]);
    const vectorStoreDialogVisible = ref(false);
    const currentVectorStore = ref<VectorStore | null>(null);
    const isEditing = ref(false);

    const handleAddPrompt = () => {
      if (formData.recommendedPrompts.length < 5) {
        formData.recommendedPrompts.push({ name: '' });
      }
    };

    const handleDeletePrompt = (index: number) => {
      formData.recommendedPrompts.splice(index, 1);
    };

    const handleAddVectorStore = () => {
      currentVectorStore.value = {
        id: '',
        name: '',
        maxResults: 5,
        similarityThreshold: 0.8
      };
      isEditing.value = false;
      vectorStoreDialogVisible.value = true;
    };

    const handleEditVectorStore = (store: VectorStore) => {
      currentVectorStore.value = { ...store };
      isEditing.value = true;
      vectorStoreDialogVisible.value = true;
    };

    const handleDeleteVectorStore = (index: number) => {
      formData.vectorStores.splice(index, 1);
    };

    const handleSaveVectorStore = () => {
      if (currentVectorStore.value) {
        if (isEditing.value) {
          const index = formData.vectorStores.findIndex(s => s.id === currentVectorStore.value?.id);
          if (index !== -1) {
            formData.vectorStores[index] = { ...currentVectorStore.value };
          }
        } else {
          formData.vectorStores.push({ ...currentVectorStore.value });
        }
        vectorStoreDialogVisible.value = false;
      }
    };

    const fetchVectorStores = async () => {
      // TODO: 从接口获取向量知识库列表
      vectorStores.value = [
        { id: '1', name: '知识库1' },
        { id: '2', name: '知识库2' }
      ];
    };

    watch(() => props.modelValue, (newVal) => {
      Object.assign(formData, newVal);
    }, { deep: true });

    watch(formData, (newVal) => {
      emit('update:modelValue', { ...newVal });
    }, { deep: true });

    const fetchModels = async () => {
      models.value = await modelsStore.fetchModels();
    };

    const fetchFunctions = async () => {
      functions.value = await functionsStore.fetchFunctions();
    };

    fetchModels();
    fetchFunctions();
    fetchVectorStores();

    return {
      formData,
      models,
      functions,
      vectorStores,
      vectorStoreDialogVisible,
      currentVectorStore,
      isEditing,
      handleAddPrompt,
      handleDeletePrompt,
      handleAddVectorStore,
      handleEditVectorStore,
      handleDeleteVectorStore,
      handleSaveVectorStore
    };
  }
});
</script>

<style lang="scss" scoped>
.recommended-prompts {
  .add-prompt {
    margin-top: 10px;
    display: flex;
    align-items: center;
    gap: 10px;

    .prompt-tip {
      color: #f56c6c;
      font-size: 12px;
    }
  }
}

.vector-stores {
  .add-vector-store {
    margin-top: 10px;
  }
}

:deep(.el-form-item__content) {
  width: 100%;
}

:deep(.el-table) {
  width: 100% !important;
}
</style> 